package m.toolkit.console;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import m.framework.utils.DateTime;
import m.framework.utils.SimpleEntry;
import m.framework.utils.StrBuilder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 命令行输出内容保存者
 * 
 * @author ming
 * @date 2014年2月23日上午9:35:26
 */
public class OutputHolder {
	private static Logger log = LoggerFactory.getLogger(OutputHolder.class);
	private int max = 0;
	private Lock lock = new ReentrantLock();
	//元素
	private List<String> elements;
	//元素插入时间
	private List<Long> times;
	private Long firstTime;
	

	public OutputHolder(int max) {
		elements = new ArrayList(max);
		times= new ArrayList(max);
		this.max = max;
	}

	public void add(String element) {
		this.add(element, System.currentTimeMillis());
	}

	public void add(String element, Long updateTime) {
		lock.lock();
		try {
			if(firstTime==null){
				firstTime=updateTime;
			}
			if (elements.size() < max) {
				elements.add(element);
				times.add(updateTime);
			} else {
				elements.remove(0);
				elements.add(element);
				
				times.remove(0);
				times.add(updateTime);
			}
		} finally {
			lock.unlock();
		}
	}

	/**
	 * 获取某个时间点后的信息
	 * 
	 * @param lastPeekTime 上次获取数据时间
	 * @param timesplit
	 * @return Entry<最新数据时间,从上次到本次产生的数据>
	 * */
	public Entry<Long, String> peek(Long lastDataTime) {
		if(lastDataTime==null){
			lastDataTime=0L;
		}
		lock.lock();
		try {
			if(times.size()==0){
				log.debug("输出结果的list内容为空");
				Entry en=new SimpleEntry(0L);
				en.setValue("");
				return en;
			}
			StrBuilder sb=new StrBuilder();
			Entry en=new SimpleEntry(times.get(times.size()-1));
			for(int i=0;i<times.size();i++){
				Long time=times.get(i);
				if(time<=lastDataTime){
					log.debug(i+"跳过"+new DateTime(time));
					continue;
				}
				sb.append(elements.get(i));
			}
			en.setValue(sb.toString());
			return en;
		} finally {
			lock.unlock();
		}
	}
	
	//第一更新记录时间
	public Long firstUpdateTime(){
		return firstTime;
	}
}
